/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package org.androidpn.server.xmpp.handler;

import java.util.List;

import org.androidpn.server.entity.FriendGroup;
import org.androidpn.server.entity.Role;
import org.androidpn.server.service.FriendGroupService;
import org.androidpn.server.service.ServiceLocator;
import org.androidpn.server.xmpp.UnauthorizedException;
import org.androidpn.server.xmpp.packet.FriendGroupPacket;
import org.androidpn.server.xmpp.packet.FriendGroupPacket.Operation;
import org.androidpn.server.xmpp.session.ClientSession;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.smack.util.StringUtils;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

/**
 * This class is to handle the TYPE_IQ jabber:iq:roster protocol.
 * 
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class IQFriendGroupHandler extends IQHandler {

	private static final String NAMESPACE = "jabber:iq:friendGroup";

	private FriendGroupService friendGroupService = null;

	/**
	 * Constructor.
	 */
	public IQFriendGroupHandler() {
		friendGroupService = (FriendGroupService) ServiceLocator
				.getService(ServiceLocator.FRIEND_GROUP_SERVICE);
	}

	/**
	 * Handles the received IQ packet.
	 * 
	 * @param packet
	 *            the packet
	 * @return the response to send back
	 * @throws UnauthorizedException
	 *             if the user is not authorized
	 */
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ reply = null;

		ClientSession session = sessionManager.getSession(packet.getFrom());

		try {
			Element query = packet.getChildElement();
			reply = IQ.createResultIQ(packet);
			String operationStr = query.elementText("operation");
			if (operationStr != null && !operationStr.equals("")) {
				Operation operation = Operation.valueOf(operationStr);
				switch (operation) {
				case deleteFriendGroup:
					break;
				case getFriendGroupsByRoleId:
					getFriendGroupsByRoleId(reply, query);
					break;
				case addFriendGroup:
					addFriendGroup(reply, query);
					break;
				default:
					reply.setError(PacketError.Condition.feature_not_implemented);
					break;
				}
			} else {
				reply = null;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			reply.setError(PacketError.Condition.feature_not_implemented);
		}
		if (reply != null) {
			session.process(reply);
		}
		return null;
	}

	private void addFriendGroup(IQ reply, Element query) {
		Long roleID = Long.valueOf(query.elementText("roleID"));
		if (roleID == null || roleID.equals(new Long(0))) {
			reply.setError(PacketError.Condition.bad_request);
			return;
		}
		Role role = new Role();
		role.setId(roleID);
		String xml = StringUtils.unescapeNode(query.elementText("friendGroup"));
		FriendGroup friendGroup = FriendGroup.fromXML(StringUtils
				.unescapeNode(query.elementText("friendGroup")));
		friendGroup.setId(null);
		friendGroup.setRole(role);
		friendGroupService.save(friendGroup);
	}

	/**
	 * 根据角色ID获取分组信息
	 * 
	 * @param reply
	 * @param query
	 * @throws DocumentException
	 */
	private void getFriendGroupsByRoleId(IQ reply, Element query)
			throws DocumentException {
		Long roleID = Long.valueOf(query.elementText("roleID"));
		List<FriendGroup> friendGroups = friendGroupService
				.getFriendGroupByRoleID(roleID);
		FriendGroupPacket friendGroupPacket = new FriendGroupPacket();
		friendGroupPacket.setFriendGroups(friendGroups);
		if (friendGroupPacket.getChildElementXML() != null) {
			Document doc = DocumentHelper.parseText(friendGroupPacket
					.getChildElementXML());
			Element element = doc.getRootElement();
			reply.setChildElement(element.createCopy());
			reply.setType(IQ.Type.result);
		}
	}

	public String getNamespace() {
		return NAMESPACE;
	}
}
